<template>

 
  <el-dialog 
    :visible.sync="visible"
    :width="dialogMaximized ? '98vw' : '1200px'"
    :fullscreen="dialogMaximized"
    :show-close="true"
    class="scm-product-dialog">
    <template #title>
      <span> </span>
      <el-button
        @click="toggleDialogMax"
        style="float: right; margin-right: 0; border: none; background: none;"
        circle
        :title="dialogMaximized ? '还原' : '最大化'"
      >
        <el-icon>
          <component :is="dialogMaximized ? 'Minus' : 'FullScreen'" />
        </el-icon>
      </el-button>
   </template>

    <!-- 1. 标题栏 -->
    <div style="font-weight: bold; font-size: 22px; color: #222; text-align: center; margin-bottom: 10px;">
      选择供应商订单入库
    </div>

    <!-- 2. 标签页 -->
    <el-tabs v-model="activeTab" style="margin-bottom: 10px;">
      <el-tab-pane label="待选" name="toSelect"></el-tab-pane>
      <el-tab-pane label="已选" name="selected"></el-tab-pane>
    </el-tabs>

    <!-- 3. 搜索框和新增按钮 -->
    <div style="display: flex; justify-content: flex-end; align-items: center; margin-bottom: 10px;">
      <el-input
        v-model="search"
        placeholder="按 enter 键搜索"
        clearable
        style="width: 240px;"
        @keyup.enter.native="handleSearch"
      />
      <el-button type="primary" style="margin-left: 10px;" @click="handleAdd">新增数据</el-button>
    </div>


    <el-select
v-model="visibleColumns"
multiple
collapse-tags
style="width: 350px; margin-bottom: 10px;"
placeholder="选择要显示的列"
>
<el-option
  v-for="col in allColumns"
  :key="col.prop"
  :label="col.label"
  :value="col.prop"
/>
</el-select>


    <!-- 5. 数据表格 -->
    <el-table
      :data="displayTableData"
      border
      style="width: 100%;"
      v-loading="loading"
      height="350"
      @selection-change="handleSelectionChange"
      :default-sort="{ prop: 'itemId', order: 'descending' }"
      :row-key="row => row.itemId"
      ref="elTable"
    >
      <el-table-column
        v-if="activeTab === 'toSelect'"
        type="selection"
        width="50"
      />
      <el-table-column
        v-for="col in allColumns.filter(c => visibleColumns.includes(c.prop))"
        :key="col.prop"
        :label="col.label"
        :prop="col.prop"
        align="center"
      />
    </el-table>

    <!-- 6. 分页控件 -->
    <div v-if="activeTab === 'toSelect'" style="display: flex; justify-content: space-between; align-items: center; margin: 16px 0 0 0;">
      <div style="color: #888;">
        已选 {{ selectedRows.length }} / 共 {{ total }} 条数据
      </div>
      <el-pagination
        background
        layout="prev, pager, next, sizes, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
    <div v-else style="color: #888; margin: 16px 0 0 0;">
      已选 {{ selectedRows.length }} 条数据
    </div>

    <!-- 7. 操作按钮区 -->
    <div slot="footer" class="dialog-footer" style="text-align: right; border-top: 1px solid #eee; padding-top: 16px; margin-top: 10px;">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="warning" style="background: orange; color: #fff; border: none;" @click="handleConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { listScmSupplierOrders, getScmSupplierOrders, delScmSupplierOrders, addScmSupplierOrders, updateScmSupplierOrders } from "@/api/scm/scmSupplierOrders";
import { listScmSupplierOrderItemsWithOrderInfo, getScmSupplierOrderItems, delScmSupplierOrderItems, addScmSupplierOrderItems, updateScmSupplierOrderItems } from "@/api/scm/scmSupplierOrderItems";
import { Minus, FullScreen } from '@element-plus/icons-vue';
export default {
  name: "ScmProductItemBySupplyOrderIdList",
  components: {
    FullScreen,
    Minus,
  },

  props: {
    visible: Boolean
  },
  data() {
    return {
      activeTab: "toSelect",
      search: "",
      loading: false,
      currentPage: 1,
      pageSize: 50,
      total: 0,
      selectedRows: [],
      allData: [],
      selectedMap: {}, // 用于全局保存已选项

      allColumns: [
      { label: 'ID', prop: 'itemId' },
      // { label: '供应商订单号', prop: 'orderId' },
      // { label: '项目产品号', prop: 'projectProductId' },
      { label: '供应商订单号', prop: 'mainOrderCode' },
      { label: '图号/型号', prop: 'scmProjectProducts.drawingNumber' },
      { label: '版本', prop: 'scmProjectProducts.version' },
      { label: '品名', prop: 'scmProjectProducts.productName' },
      { label: '材质', prop: 'scmProjectProducts.material' },
      { label: '尺寸', prop: 'size' },
      { label: '规格', prop: 'scmProjectProducts.specification' },
      { label: '颜色', prop: 'scmProjectProducts.color' },
      { label: '单价类型', prop: 'unitPriceType' },
      { label: '单价', prop: 'unitPrice' },
      { label: '订单数量', prop: 'quantity' },
      { label: '已入库量', prop: 'quantityInLib' },
       
      { label: '金额', prop: 'amount' }
    ],
    visibleColumns: [
      
      'itemId','orderId', 'projectProductId','mainOrderCode','scmProjectProducts.drawingNumber', 'scmProjectProducts.version', 'scmProjectProducts.productName', 'quantity', 'quantityInLib','amount'
    ],
    dialogMaximized: false,
    };
  },
  computed: {
    tableData() {
      // 搜索和分页
      let filtered = this.allData.filter(item =>
        !this.search ||
        (item.productName && item.productName.includes(this.search)) ||
        (item.drawingNumber && item.drawingNumber.includes(this.search)) ||
        (item.model && item.model.includes(this.search)||
        (item.mainOrderCode && item.mainOrderCode.includes(this.search)))
      );
      this.total = filtered.length;
      const start = (this.currentPage - 1) * this.pageSize;
      return filtered.slice(start, start + this.pageSize);
    },
    displayTableData() {
      // 待选tab显示tableData，已选tab显示所有已选
      if (this.activeTab === "toSelect") {
        return this.tableData;
      } else {
        return Object.values(this.selectedMap);
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.currentPage = 1;
        this.fetchData();
        this.$nextTick(() => {
          if (this.activeTab === "toSelect") this.setTableSelection();
        });
      }
    },
    activeTab(val) {
      // 切换到已选时，取消表格的多选框选中状态
      if (val === "selected" && this.$refs.elTable) {
        this.$refs.elTable.clearSelection();
      }
      if (val === "toSelect" && this.$refs.elTable) {
        this.$nextTick(() => {
          this.setTableSelection();
        });
      }
    }
  },
  methods: {

    fetchData() {
      this.loading = true;
      listScmSupplierOrderItemsWithOrderInfo({ pageNum: this.currentPage, pageSize: this.pageSize, search: this.search }).then(res => {
        this.allData = res.rows || [];
        this.total = res.total || this.allData.length;
        this.loading = false;
        this.$nextTick(() => {
          if (this.activeTab === "toSelect") this.setTableSelection();
        });
        console.log(res.rows); // 检查每条数据是否有这些字段
      }).catch(() => {
        this.loading = false;
      });
    },
    setTableSelection() {
      if (this.$refs.elTable) {
        this.$refs.elTable.clearSelection();
        this.tableData.forEach(row => {
          if (this.selectedMap[row.itemId]) {
            this.$refs.elTable.toggleRowSelection(row, true);
          }
        });
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    handleAdd() {
      this.$message.info("点击了新增数据");
    },
    handleSelectionChange(val) {
      // 先把当前页所有数据从 map 里移除
      this.tableData.forEach(item => {
        if (this.selectedMap[item.itemId]) {
          delete this.selectedMap[item.itemId];
        }
      });
      // 再把当前页勾选的加进去
      val.forEach(item => {
        this.selectedMap[item.itemId] = item;
      });
      // 更新 selectedRows
      this.selectedRows = Object.values(this.selectedMap);
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchData();
    },
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchData();
    },
    handleCancel() {
      this.$emit("select", []);
      this.$emit("update:visible", false);
    },
    handleConfirm() {
      this.$emit("select", this.selectedRows);
      this.$emit("update:visible", false);
    },
   
    toggleDialogMax() {
    this.dialogMaximized = !this.dialogMaximized;
  },
  }
};
</script>

<style scoped>
.scm-product-dialog .el-dialog__body {
  padding-top: 0;
}
</style>